package com.lyj.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyj.common.core.constants.CacheConstants;
import com.lyj.common.core.enums.ResultCode;
import com.lyj.friend.domain.question.Question;
import com.lyj.friend.mapper.question.QuestionMapper;
import com.lyj.redis.service.RedisService;
import com.lyj.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-09-18
 * Time: 11:17
 */
@Component
public class QuestionCacheManager {
    @Autowired
    private RedisService redisService;

    @Autowired
    private QuestionMapper questionMapper;

    public Long getListSize(){
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }
    public void refreshCache(){
        //虽然返回的是question对象，但是对象中只有questionId这一个值，优化查询
        List<Question> questionList = questionMapper.selectList(new QueryWrapper<Question>()
                .lambda()
                .select(Question::getQuestionId).orderByDesc(Question::getCreateTime));
        if(CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();
        //尾插或者批量插入
        redisService.rightPushAll(CacheConstants.QUESTION_LIST,questionIdList);
    }
    public Long preQuestion(Long questionId){
        //获得当前题目的下标
        Long index =redisService.indexOfForList(CacheConstants.QUESTION_LIST,questionId);
        if(index == 0){
            //已经是第一题
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index-1,Long.class);
    }
    public Object nextQuestion(Long questionId) {
        Long index =redisService.indexOfForList(CacheConstants.QUESTION_LIST,questionId);
        Long lastIndex = getListSize() - 1;
        if(index == lastIndex){
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index+1,Long.class);
    }
}
